import React from 'react';
import {Message} from 'antd';
import config from '../../config';
import {CANCEL_ORDER, FETCH_ORDER_LIST} from '../../constants/userTypes';
import Cookies from 'js-cookie';
import {
    setupWebViewJavascriptBridge,
    bridgeCallHandler,
    setItem,
    isAndroid,
    isWeiXin
} from '../../utils';

/**
 * 加载公共组件
 * */
import MainSection from '../../components/MainSection/MainSection';
import Price from '../../components/Price/Price';
import InfiniteScroll from '../../components/InfiniteScroll/InfiniteScroll';

/**
 * 加载样式或图片文件
 * */
import './sass/actMan.scss';

class ActMan extends React.Component {
    static contextTypes = {
        router: React.PropTypes.object.isRequired
    };

    constructor(props) {
        super(props);
        // this.handleChangeTab = this.handleChangeTab.bind(this);
        this.loadFunc = this.loadFunc.bind(this);

        this.state = {
            curStatus: 0,
            orderList: [],
            isEnd: false,
            isLoading: false,
            isNoData: false,

            payStatus: '',
            signStatus: '',
            page: 0,
            size: 3
            // totalPage: 1
        };
    }

    componentDidMount() {
        let _this = this;
        _this.loadFunc();


        // if (isWeiXin()) {
        //     _this.loadFunc();
        // } else {
        //     // bridgeCallHandler('accessToken', {}, function (data) {
        //     //     alert(data)
        //     //     alert(data.accesstoken)
        //     // });
        //     if (isAndroid()) {
        //         let token = Cookies.get('accesstoken');
        //         if (token) {
        //             setItem('token', token);
        //             _this.loadFunc();
        //         } else {
        //             Message.info('用户未登录')
        //         }
        //
        //     } else {
        //         setupWebViewJavascriptBridge(function (bridge) {
        //             if (isAndroid()) {
        //                 if (window.WVJBCallbacks) { //注册默认接收android回调函数,ios不能加
        //                     bridge.init(function (message, responseCallback) {
        //                         var data = {'Javascript Responds': 'Wee!'};
        //                         responseCallback(data);
        //                     })
        //                 }
        //             }
        //             bridge.registerHandler("accessTokenCallBack", function (data, responseCallback) {
        //                 let token = data.accesstoken;
        //                 if (token) {
        //                     setItem('token', token);
        //                     setTimeout(() => {
        //                         _this.loadFunc();
        //                     }, 300)
        //                 } else {
        //                     Message.info('用户未登录')
        //                 }
        //             })
        //         });
        //     }
        // }

    }

    loadFunc() {
        const {actions} = this.props;
        this.setState({
            isLoading: true,
            page: this.state.page + 1
        }, () => {
            actions.fetchOrderList(
                {
                    payStatus: this.state.payStatus,
                    signStatus: this.state.signStatus,
                    page: this.state.page,
                    size: this.state.size
                }).then(response => {
                if (response.type === FETCH_ORDER_LIST) {
                    // console.log(this.state.page);
                    if (response.orderList.length === 0 && this.state.page === 1) {
                        // 没有数据
                        this.setState({isNoData: true});
                    } else if (response.orderList.length < this.state.size) {
                        // 没有更多数据
                        this.setState({isEnd: true});
                    }
                    this.setState({
                        orderList: [...this.state.orderList, ...response.orderList],
                        isLoading: false
                    });
                }
            });
        });
    }

    handleChangeTab(index) {
        const {actions} = this.props;
        if (index === this.state.curStatus) return;

        let data = {
            payStatus: '',
            signStatus: ''
        };
        switch (index) {
            case 0:
                break;
            case 1:
                data.payStatus = 101;
                break;
            case 2:
                data.signStatus = 101;
                break;
            case 3:
                data.signStatus = 102;
                break;
            case 4:
                data.payStatus = 103;
                break;
            default:
                break;
        }

        this.setState({
            orderList: [],
            isEnd: false,
            isNoData: false,
            curStatus: index,
            payStatus: data.payStatus,
            signStatus: data.signStatus,
            page: 0
        }, () => {
            this.loadFunc();
        });

    }

    handleGoPay(number, eventId, payPrice) {
        if (isWeiXin()) {
            this.context.router.push({
                pathname: "/activityList/" + eventId + "/applyAct",
                state: {
                    comeFrom: 'order',
                    number: number,
                    eventId: eventId,
                    payPrice: payPrice
                }
            })
        } else {
            bridgeCallHandler('jumpOrderPay', {eventId: eventId});
        }

    }

    handleGoAct(eventId) {
        if (isWeiXin()) {
            this.context.router.push({
                pathname: "/activityList/" + eventId
            })
        } else {
            bridgeCallHandler('jumpActivityDetail', {eventId: eventId});
        }

    }

    handleCancelOrder(number) {
        const {actions} = this.props;
        if (confirm('确认取消改订单?')) {
            actions.cancelOrder({number: number}).then(res => {
                if (res.type === CANCEL_ORDER) {
                    if (res.code === 20000) {
                        Message.info('已取消');
                        this.setState({
                            orderList: this.state.orderList.map(item => item.number === number ? {
                                ...item,
                                payStatus: 103
                            } : item)

                        })
                    }
                }
            });
        }

    }


    render() {
        return (
            <MainSection className="act-man" title="我的订单">
                <div className="simple-tabs">
                    {
                        config.ORDER_STATUS_ARRAY.map((item, index) => {
                            return (
                                <span key={index}
                                      className={"tab-item " + (this.state.curStatus === index ? "cur" : "")}
                                      onClick={this.handleChangeTab.bind(this, index)}>{item}</span>
                            )
                        })
                    }
                </div>
                <InfiniteScroll
                    loadFunc={this.loadFunc}
                    isEnd={this.state.isEnd}
                    isLoading={this.state.isLoading}
                    isNoData={this.state.isNoData}>
                    <div className="order-list">
                        {
                            this.state.orderList.map((item, index) => {
                                let isScore = item.type === 102;
                                let price = isScore ? item.point : item.price;
                                let payPrice = isScore ? item.payPoint : item.payPrice;
                                let childNum = isScore ? Math.ceil(item.payPoint / item.point) : Math.ceil(item.payPrice / item.price)
                                return (
                                    <div key={index} className="order-item">
                                        <div className="title">
                                            <span>订单编号: {item.number}</span>
                                            <span className={"status style" + item.payStatus}>
                                            {config.ORDER_STATUS[item.payStatus]}
                                        </span>
                                        </div>
                                        <div className="act-info">
                                            <a onClick={this.handleGoAct.bind(this, item.eventId)}>
                                                <img src={item.image} alt=""/>
                                                <div>
                                                    <p className="act-title">{item.name}</p>
                                                    <p className="act-price"><Price num={price} isScore={isScore}
                                                                                    size="sm"/></p>
                                                </div>
                                            </a>

                                        </div>
                                        <div className="total">
                                            共{childNum}位儿童 合计:<Price num={payPrice} isScore={isScore} size="sm"/>
                                        </div>
                                        {
                                            [101].indexOf(parseInt(item.payStatus)) > -1 ? (
                                                <div className="control-bar">
                                                    <button className="cancel"
                                                            onClick={this.handleCancelOrder.bind(this, item.number)}>
                                                        取消订单
                                                    </button>
                                                    <button className="confirm"
                                                            onClick={this.handleGoPay.bind(this, item.number, item.eventId, item.payPrice)}>
                                                        立即支付
                                                    </button>
                                                </div>
                                            ) : null
                                        }

                                    </div>
                                )
                            })
                        }
                    </div>
                </InfiniteScroll>


            </MainSection>
        );
    }
}

export default ActMan;